<script lang="ts" setup>

import type {RepliesData} from "../../network/types/TopicDetail.ts";
import {ref, watch} from "vue";
import type {Attachment, ReplyInfo} from "../../network/types/Reply.ts";
import type {UserInfo} from "../../network/types/User.ts";
import {replaceAvatar} from "../../store/UserStore.ts";
import {ReplyStatus} from "../../network/types/ReplyStatus.ts";
import {ItemType, type ItemTypeInfo} from "../../network/types/Item.ts";
import {useRoute, useRouter} from "vue-router";
import {ReplyListRoute} from "../../router";
import ContentRender from "../content/ContentRender.vue";
import {decode} from "../../network/utils/StrUtils.ts";
import TopicReadRoute from "../routes/TopicReadRoute.vue";
import type {PostProps} from "../post/PostForm.vue"
import PostForm from "../post/PostForm.vue";
import type {NgaLocation} from "../../network/types/NgaLocation.ts";
import ReplyAuthorHeader from "./ReplyAuthorHeader.vue";
import ReplyAgree from "./ReplyAgree.vue";
import ReplyToolIcon from "./ReplyToolIcon.vue";
import ReplyTime from "./ReplyTime.vue";
import ReplySingleDialog from "./ReplySingleDialog.vue";
import PostAttachment from "../post/PostAttachment.vue";
import {copyText} from "../../utils/Utils.ts";
import ReplyVote from "./ReplyVote.vue";
import ReplyFavorDialog from "./ReplyFavorDialog.vue";
import ItemTabs from "../items/ItemTabs.vue";
import {useResourceStore} from "../../store/ResourceStore.ts";

const props = defineProps<RepliesData>();
const router = useRouter()
const route = useRoute()
const resourceStore = useResourceStore();
const emit = defineEmits(['refresh'])
// 显示快速发帖弹窗
const showPostDialog = ref(false)
// 显示单个回复弹窗
const postProps = ref<PostProps>()
const showSingleReplyDialog = ref(false)
const singleReplyId = ref<number>()
const showAttachmentDialog = ref(false)
const showItemDialog = ref(false)
const showFavorDialog = ref(false)
const showSourceCodeDialog = ref(false)
const addFavorPid = ref<number>()
// 道具使用目标的pid
const itemTargetPid = ref<number>()
const itemTargetTid = ref<number>()
const attachments = ref<Attachment[]>()
const sourceCode = ref<string>()

defineExpose({showPostDialog,})


const quickPost = (params: PostProps) => {
  postProps.value = params
  showPostDialog.value = true
}
const sourceCodeDialog = (e: any) => {
  showSourceCodeDialog.value = true
  sourceCode.value = e.code
}
const onUseItem = ({tid, pid}: { tid: number, pid: number }) => {
  itemTargetTid.value = tid
  itemTargetPid.value = pid
  showItemDialog.value = true
}

const onPostError = (error: any) => {
  console.error(error)
}
const onPostSuccess = (location: NgaLocation) => {
  console.log(location)
  showPostDialog.value = false

  if (postProps.value?.comment) {
    //  如果是评论，原地刷新
    emit('refresh')
  } else {
    // 非评论，跳转到新楼层
    router.push({name: ReplyListRoute.LIST, params: {tid: location.tid}, query: {page: 'e'}, hash: '#P' + location.pid})
  }
}
const rowClass = (index: number) => {
  if (index % 2 === 0) {
    return "item-bg-color0"
  } else {
    return "item-bg-color1"
  }
}

const contentClass = (item: ReplyInfo) => {
  const user = userByReply(item);
  const res = [] as string[]

  if (item.punished) res.push('punished-in-topic')
  if (user?.memberId === 5) res.push('warden-content')
  if (user?.memberId === 3) res.push('titan-content')

  return res.join(' ')
}

const userByReply = (item: ReplyInfo): UserInfo => props.userMap.users[Number(item.authorUid)]
const avatarByReply = (item: ReplyInfo): string | undefined => {
  const userInfo = userByReply(item);

  const avatarBuff = resourceStore.avatarBuffs.find(it => it.id === userInfo?.avatarBuffId);
  const avatars = userInfo?.avatars;

  // 变身头像
  if (avatarBuff) {
    return avatarBuff.url.replace('https://img4.nga.178.com/', '/static/res/')
  }

  // 从头像数组中随机选出一个
  if (avatars && avatars.length > 0) {
    return replaceAvatar(avatars[Math.floor(Math.random() * avatars.length)])
  }
}
const groupByReply = (item: ReplyInfo): string => {
  const user = userByReply(item)
  return `${props.userMap.groups[user.memberId]}(${user.memberId})`
}

const medalsByReply = (item: ReplyInfo): ItemTypeInfo[] | undefined => {
  const medals = userByReply(item)?.medalId;
  if (!medals) return undefined
  return props.userMap.medals.filter(medal => medals.includes(medal.subTypeId))
}

const reputationByReply = (item: ReplyInfo): string => {
  const user = userByReply(item)
  const value = (props.userMap.reputationId ? user.reputation[props.userMap.reputationId] : 0) || 0
  // 声望等级
  const name = props.levels?.find(i => value >= i.rank)?.name;

  return name ? `${name}(${value})` : value.toString()
}

const showSingleReply = (pid: number) => {
  singleReplyId.value = pid
  showSingleReplyDialog.value = true
}
const showAttachments = (value: Attachment[]) => {
  attachments.value = value
  showAttachmentDialog.value = true
}
const addFavor = (param: any) => {
  showFavorDialog.value = true
  addFavorPid.value = param.pid
}

watch(route, () => {
  showSingleReplyDialog.value = false
})

//   todo 添加快捷键：  w + s 为选中回复 ； q、e、r、t、z、c分别为对选中回复的快速操作：引用，编辑，回复，贴条，赞、踩

</script>

<template>
  <div>
    <table class="reply-table">
      <template v-for="(item, index) in replies" :key="index">
        <tr v-if="item.blocked" :id="'P'+item.replyId" :class="rowClass(index)" @click="item.blocked=false">
          <td :id="'F'+ item.floorNumber" class="clickable" colspan="2" style="text-align: center">
            <el-text type="danger">本条回复已被屏蔽，点击临时解除</el-text>
          </td>
        </tr>
        <tr v-else :class="rowClass(index)">
          <td>
            <!--用户名-->
            <reply-author-header
                :anonymous-name="userMap.anonymous[Number(item.authorUid)]"
                :reply="item"
                :topic-author-id="topic.authorUid"
                :user="userByReply(item)"
            />

            <!--头像-->
            <div v-if="!item.anonymous && userByReply(item)?.avatars && item.content" style="text-align: center">
              <el-image :src="avatarByReply(item)" class="user-avatar"/>
            </div>

            <!--   基本信息: 用户组，声望，威望，发帖数-->
            <div v-if="!item.anonymous && userByReply(item)">
              <el-descriptions :column="2">
                <el-descriptions-item label="用户组">{{ groupByReply(item) }}</el-descriptions-item>
                <el-descriptions-item label="声望">{{ reputationByReply(item) }}</el-descriptions-item>
                <el-descriptions-item label="威望">{{ userByReply(item).prestige / 10 }}</el-descriptions-item>
                <el-descriptions-item label="发帖数">{{ userByReply(item).postCount }}</el-descriptions-item>
                <el-descriptions-item v-if="medalsByReply(item)" label="徽章">
                  <el-tooltip v-for="medal in  medalsByReply(item)">
                    <template #content>
                      <h4>{{ medal.name }}</h4>
                      <div>{{ medal.description }}</div>
                    </template>
                    <el-image :src="medal.url.replace('https://img4.nga.178.com/','/static/res/')" class="user-medal"/>
                  </el-tooltip>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </td>
          <td :id="'P'+item.replyId">
            <!--楼层顶部，楼层号，赞踩数，发布/修改时间，回复状态-->
            <div :id="'F'+ item.floorNumber" class="level-header">
              <span>
                <topic-read-route v-if="item.replyId" :pid="item.replyId" :to="route.name===ReplyListRoute.SINGLE ? 1:undefined">
                  <el-tag>{{ item.floorNumber }}</el-tag>
                </topic-read-route>
                <el-tag v-else>{{ item.floorNumber }}</el-tag>

                <!--赞踩-->
                <reply-agree :reply="item"/>
                <reply-time :reply="item"/>
                <el-tag v-if=" item.client">{{ item.client }}</el-tag>
                <el-tag v-if="item.replyToId" class="clickable" type="warning" @click="router.push({name: ReplyListRoute.SINGLE, params: {pid: item.replyToId}, query: {to: '1'}})">
                  回复目标
                </el-tag>
                <el-tag v-if="item.attachments" class="clickable" type="success" @click=" showAttachments(item.attachments)">附件列表</el-tag>
                <!--   回复状态-->
                <el-tag v-if="item.status?.includes(ReplyStatus.HIDDEN)" type="danger">隐藏</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.NO_HINT)" type="primary">不再提示</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.FREE_EDIT)" type="primary">编辑</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.SELF_REPLY)" type="primary">自回</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.VERIFYING)" type="warning">审核中</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.VERIFYING_2)" type="warning">审核中2</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.NOT_VERIFIED)" type="danger">审核不通过</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.LOCKED)" type="danger">锁定</el-tag>
                <el-tag v-if="item.status?.includes(ReplyStatus.PUNISHED)" type="danger">处罚</el-tag>
                <el-tag v-if="item.punished" type="warning">主题内被处罚</el-tag>
              </span>
              <span v-if="item.replyId!=undefined">
                <!--   快速回复：评论、引用、回复-->
                <reply-tool-icon
                    :anonymous="userMap.anonymous[Number(item.authorUid)]"
                    :reply="item"
                    :topic="topic"
                    :username="userMap.users[Number(item.authorUid)]?.username"
                    @source="sourceCodeDialog"
                    @use-item="onUseItem"
                    @quick-post="quickPost"
                    @add-favor="addFavor"
                />
              </span>
            </div>
            <!--标题-->
            <h3 v-if="item.title">{{ decode(item.title) }}</h3>
            <!--正文-->
            <div :class="contentClass(item)">
              <!--{{ item.content }}-->
              <content-render :data="item.nodes || []" @SingleReply="showSingleReply"/>
            </div>
            <!--礼物-->
            <div v-if="item.gifts">
              <h4>礼物</h4>
              <el-badge v-for="gift in item.gifts" :value="gift.count">
                <!--https://img4.nga.178.com/ngabbs/nga_classic/items/5_17.png-->
                <el-image :src="gift.url.replace('https://img4.nga.178.com/','/static/res/')"/>
              </el-badge>
            </div>
            <!--操作记录-->
            <div v-if="item.logs">
              <h4>操作记录</h4>
              <div>
                <template v-for="log in item.logs">
                  <el-tag v-if="log.type==='punishment'" type="danger">
                    <span v-if="log.forumId">在版面 ({{ log.forumId }})</span>
                    <span> 禁言 {{ log.days }} 天</span>
                    <span v-if="log.reputation"> 扣除声望 {{ log.reputation }}</span>
                    <span> 理由: {{ log.reason }}</span>
                  </el-tag>
                  <el-tag v-else-if="log.type==='canceled'" type="warning">
                    取消操作
                  </el-tag>
                  <el-tag v-else-if="log.type==='reward'" :type="log.reputation>=0 ? 'success':'warning'">
                    评分
                    <span v-if="log.reputation">{{ log.reputation }} 声望 </span>
                    <span v-if="log.prestige">{{ log.prestige / 10 }} 威望 </span>
                    <span v-if="log.money">{{ log.money }} 铜币 </span>
                    {{ log.reason }}
                  </el-tag>
                </template>
              </div>
            </div>
            <!-- 贴条 -->
            <div v-if="item.comment" class="sub-replies">
              <h4>贴条</h4>
              <table class="reply-table">
                <tr v-for="(it, i) in item.comment" :key="i" :class="rowClass(i)">
                  <td>
                    <!--用户名-->
                    <reply-author-header
                        :anonymous-name="userMap.anonymous[Number(it.authorUid)]"
                        :reply="it"
                        :topic-author-id="topic.authorUid"
                        :user="userByReply(it)"
                    />
                    <div v-if="!it.anonymous && userByReply(it)?.avatars && it.content" style="text-align: center">
                      <el-image :src="avatarByReply(it)" class="user-avatar"/>
                    </div>
                  </td>
                  <td>
                    <div class="level-header">
                      <span>
                        <reply-agree :reply="it"/>
                        <reply-time :reply="it"/>
                      </span>
                      <span>
                        <!--   快速回复：评论、引用、回复-->
                        <reply-tool-icon
                            :anonymous="userMap.anonymous[Number(it.authorUid)]"
                            :reply="it"
                            :topic="topic"
                            :username="userMap.users[Number(it.authorUid)]?.username"
                            @source="sourceCodeDialog"
                            @use-item="onUseItem"
                            @quick-post="quickPost"
                        />
                      </span>
                    </div>
                    <div>
                      <content-render :data="it.nodes || []" @SingleReply="showSingleReply"/>
                    </div>
                  </td>
                </tr>
              </table>
            </div>
            <!-- 热评 -->
            <div v-if="item.hotReplies" class="sub-replies">
              <h4>热评</h4>
              <table class="reply-table">
                <tr v-for="(it, i) in item.hotReplies" :key="i" :class="rowClass(i)">
                  <td>
                    <!--用户名-->
                    <reply-author-header
                        :anonymous-name="userMap.anonymous[Number(it.authorUid)]"
                        :reply="it"
                        :topic-author-id="topic.authorUid"
                        :user="userByReply(it)"
                    />
                    <div v-if="!it.anonymous && userByReply(it)?.avatars && it.content" style="text-align: center">
                      <el-image :src="avatarByReply(it)" class="user-avatar"/>
                    </div>
                  </td>
                  <td>
                    <div class="level-header">
                      <span>
                        <el-tag class="clickable" type="warning" @click="router.push({name: ReplyListRoute.SINGLE, params: {pid: it.replyId}, query: {to: '1'}})">跳转</el-tag>
                        <reply-agree :reply="it"/>
                        <reply-time :reply="it"/>
                      </span>
                      <span>
                        <!--   快速回复：评论、引用、回复-->
                        <reply-tool-icon
                            :anonymous="userMap.anonymous[Number(it.authorUid)]"
                            :reply="it"
                            :topic="topic"
                            :username="userMap.users[Number(it.authorUid)]?.username"
                            @source="sourceCodeDialog"
                            @use-item="onUseItem"
                            @quick-post="quickPost"
                        />
                      </span>
                    </div>
                    <div>
                      <content-render :data="it.nodes || []" @SingleReply="showSingleReply"/>
                    </div>
                  </td>
                </tr>
              </table>
            </div>
            <!--  投票 -->
            <div v-if="item.vote" style="margin: 10px">
              <reply-vote :data="item.vote" :tid="item.topicId"/>
            </div>
          </td>
        </tr>
      </template>
    </table>

    <!--快速回复弹窗-->
    <el-dialog v-model="showPostDialog" :close-on-click-modal="false" append-to-body class="bg-color" width="70%">
      <post-form v-if="showPostDialog&&postProps"
                 :action="postProps.action"
                 :comment="postProps.comment"
                 :pid="postProps.pid"
                 :tid="postProps.tid"
                 @error="onPostError"
                 @success="onPostSuccess"
      />
    </el-dialog>
    <!--源码弹窗-->
    <el-dialog v-model="showSourceCodeDialog" append-to-body class="bg-color" width="70%">
      <template #header>
        <!--  复制源码-->
        <el-button v-if="sourceCode" type="primary" @click="copyText(sourceCode,'源码')">复制源码</el-button>
      </template>
      <div style=" white-space: pre-line">{{ sourceCode }}</div>
    </el-dialog>
    <!--附件弹窗-->
    <el-dialog v-model="showAttachmentDialog" append-to-body class="bg-color" title="附件列表" width="70%">
      <post-attachment
          v-if="attachments"
          :data="attachments"
          :description="(i: Attachment)=>i.description"
          :filename="(i: Attachment)=>i.originalFilename"
          :size="(i: Attachment)=>`${i.size} KB`"
          :thumbs="(i: Attachment)=>i.thumbs"
          :uri="(i: Attachment)=>'./'+i.thumbs[0]"
          @insert="copyText($event[0],'论坛代码')"
      />
    </el-dialog>
    <!--单个回复弹窗-->
    <reply-single-dialog v-model="showSingleReplyDialog" :pid="singleReplyId"/>
    <!--收藏弹窗-->
    <reply-favor-dialog v-model="showFavorDialog" :pid="addFavorPid" :tid="topic.topicId"/>
    <!-- 道具弹窗-->
    <el-dialog v-model="showItemDialog" title="使用道具" width="70%">
      <item-tabs :item-type="ItemType.TO_REPLY" :pid="itemTargetPid" :tid="itemTargetTid"/>
    </el-dialog>
  </div>
</template>

<style scoped>

.level-header {
  display: flex;
  justify-content: space-between;
}


.user-medal {
  width: 20px;
  margin-right: 3px;
}

.sub-replies {
  margin: 10px;
}
</style>
